package com.xh.one2one.lesson.service.impl;

import com.xh.bussiness.permission.bean.request.QueryUserRequest;
import com.xh.bussiness.permission.model.User;
import com.xh.bussiness.permission.model.UserSchool;
import com.xh.bussiness.permission.service.IUserSchoolService;
import com.xh.bussiness.permission.service.IUserService;
import com.xh.bussiness.resource.model.Material;
import com.xh.bussiness.resource.service.IMaterialService;
import com.xh.bussiness.system.model.GroupUser;
import com.xh.bussiness.system.service.IGroupUserService;
import com.xh.core.util.DateUtils;
import com.xh.core.util.UserUtils;
import com.xh.one2one.lesson.bean.request.LessonAuditRequest;
import com.xh.one2one.lesson.bean.request.LessonTimesAuditRequest;
import com.xh.one2one.lesson.bean.request.LessonTimesHisRequest;
import com.xh.one2one.lesson.bean.request.LessonTimesRequest;
import com.xh.one2one.lesson.model.LessonAudit;
import com.xh.one2one.lesson.dao.LessonAuditMapper;
import com.xh.one2one.lesson.model.LessonTimesHis;
import com.xh.one2one.lesson.service.ILessonAuditService;
import com.xh.core.service.impl.BaseServiceImpl;
import com.xh.one2one.lesson.service.ILessonTimesHisService;
import com.xh.one2one.lesson.service.ILessonTimesService;
import com.xh.one2one.teachHandout.bean.dto.HandoutDto;
import com.xh.one2one.teachHandout.bean.request.TeachTimesHandoutRelationRequest;
import com.xh.one2one.teachHandout.model.TeachTimesHandoutRelation;
import com.xh.one2one.teachHandout.service.ITeachTimesHandoutRelationService;
import com.xh.one2one.teachHandout.service.ITeachTimesService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.core.bean.XhPage;
import com.xh.core.util.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 备课审核 服务实现类
 * </p>
 *
 * @author TW
 * @since 2021-04-22
 */
@Service
public class LessonAuditServiceImpl extends BaseServiceImpl<LessonAuditMapper, LessonAudit> implements ILessonAuditService {

    @Autowired
    private IUserSchoolService userSchoolService;
    @Autowired
    private IGroupUserService groupUserService;
    @Autowired
    private IUserService userService;
    @Autowired
    private ITeachTimesHandoutRelationService teachTimesHandoutRelationService;
    @Autowired
    private IMaterialService materialService;
    @Autowired
    private ITeachTimesService teachTimesService;
    @Autowired
    private ILessonTimesService lessonTimesService;
    @Autowired
    private ILessonTimesHisService lessonTimesHisService;

    @Override
    public XhPage queryLessonAuditPage(XhPage page, LessonAuditRequest bean) {

        if (StringUtils.isEmpty(bean.getCreatorId())) {
            //根据校区或分组查询用户，没传参数默认按当前用户所属校区分组进行查询
            QueryUserRequest userRequest = new QueryUserRequest();
            if (StringUtils.isEmpty(bean.getSchoolId())) {
                List<UserSchool> schools = userSchoolService.queryUserSchoolByUserId(UserUtils.getCurrentUserId());
                if (!CollectionUtils.isEmpty(schools)) {
                    userRequest.setSchoolIds(schools.stream().map(item -> item.getSchoolId()).collect(Collectors.toList()));
                }
            } else {
                userRequest.setSchoolId(bean.getSchoolId());
            }
            if (StringUtils.isEmpty(bean.getGroupId())) {
                if (StringUtils.isEmpty(bean.getSchoolId()) && CollectionUtils.isEmpty(userRequest.getSchoolIds())) {
                    List<GroupUser> groupUsers = groupUserService.queryGroupUserByUserId(UserUtils.getCurrentUserId());
                    if (!CollectionUtils.isEmpty(groupUsers)) {
                        userRequest.setGroupIds(groupUsers.stream().map(item -> item.getUserId()).collect(Collectors.toList()));
                    }
                }
            } else {
                userRequest.setGroupId(bean.getGroupId());
            }
            List<User> users = userService.queryUserList(userRequest);
            if (StringUtils.isEmpty(userRequest.getSchoolId()) && StringUtils.isEmpty(userRequest.getGroupId())
                    && CollectionUtils.isEmpty(userRequest.getGroupIds()) && CollectionUtils.isEmpty(userRequest.getSchoolIds()) && CollectionUtils.isEmpty(users)) {
                return page;
            }
            bean.setCreatorIds(users.stream().map(item -> item.getId()).collect(Collectors.toList()));
        }

        return (XhPage) this.dao.selectLessonAuditPage(page,bean);
    }

    @Override
    public List queryLessonAudit(LessonAuditRequest bean) {
        QueryWrapper qw=new QueryWrapper<LessonAudit>();
        //拼装条件
        qw=prepareParams(bean, qw);

        return this.dao.selectList(qw);
    }

    @Override
    public HandoutDto queryDetails(LessonAuditRequest bean) {
        HandoutDto handoutDto = new HandoutDto();
        String id = bean.getIndexId();
        TeachTimesHandoutRelationRequest relationRequest = new TeachTimesHandoutRelationRequest();
        relationRequest.setIndexId(id);
        List<TeachTimesHandoutRelation> timesHandoutRelation = teachTimesHandoutRelationService.queryList(relationRequest);
        if(!CollectionUtils.isEmpty(timesHandoutRelation)) {
            TeachTimesHandoutRelation handoutRelation = timesHandoutRelation.get(0);
            Integer type = handoutRelation.getType();
            String handoutId = handoutRelation.getHandoutId();

            handoutDto.setHandoutId(handoutId);
            handoutDto.setType(type);
            handoutDto.setCopyHandout(handoutRelation.getCopyHandout());
            if (1 == type) {
                //type:1 查询上传的讲义，获取path
                Material material = materialService.getById(handoutId);
                handoutDto.setName(material.getFileName());
                handoutDto.setPath(material.getFilePath());

            } else {
                //type:2,3  查询自建讲义，获取讲义的知识元，知识点内容
                handoutDto.setChilds(teachTimesService.queryHandoutContent(handoutId));
            }
        }
        return handoutDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(LessonAuditRequest request) throws Exception {
        String handoutId = request.getHandoutId();
        String indexId = request.getIndexId();
        String lessonId = request.getLessonId();

        LessonAudit audit = new LessonAudit();
        BeanUtils.copyProperties(request,audit);
        audit.setBindVersion(1);
        //默认未审核状态
        audit.setStatus(0);
        audit.setClassTime(DateUtils.parse(request.getClassTime(),"yyyy-MM-dd HH:mm:ss"));
        if(!StringUtils.isEmpty(request.getHandoutId())){
            Material material = materialService.getById(handoutId);
            if (null == material) {
                throw new Exception("讲义不存在！");
            }
            audit.setTitle(material.getFileName());
        }
        if(null == audit.getId()){
            this.insert(audit);
        }else{
            this.update(audit);
        }

    }

    @Override
    public LessonAudit queryOne(LessonAuditRequest bean) {
        QueryWrapper qw=new QueryWrapper<LessonAudit>();
        //拼装条件
        qw=prepareParams(bean, qw);
        return this.dao.selectOne(qw);
    }


    /**
     * 准备条件
     * @param bean
     * @param qw
     */
    private QueryWrapper prepareParams(LessonAuditRequest bean, QueryWrapper qw) {
        if(bean.getIds()!=null&&bean.getIds().length>0){
            qw.in("id",bean.getIds());
        }
        if(!StringUtils.isEmpty(bean.getLessonId())){
            qw.eq("lesson_id",bean.getLessonId());
        }
        if(!StringUtils.isEmpty(bean.getLessonThirdId())){
            qw.eq("lesson_third_id",bean.getLessonThirdId());
        }
        return qw;
    }
}
